// Copyright 2023 Huawei Cloud Computing Technology Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "VmiBuffer.h"
#include <cstdlib>
#include <cstddef>
#include "Log/logging.h"

using namespace std;

/**
 * @brief: constuctor
 * @param [in] pointer: pointer
 * @param [in] bufferSize: bufferSize
 */
VmiBuffer::VmiBuffer(uint8_t* pointer, const size_t bufferSize)
{
    m_pointer = pointer;
    m_bufferSize = bufferSize;
}

/**
 * @brief: get pointer
 * @return: pointer
 */
uint8_t* VmiBuffer::GetPointer() const
{
    return m_pointer;
}

/**
 * @brief: get size
 * @return: size
 */
size_t VmiBuffer::GetSize() const
{
    return m_bufferSize;
}

/**
 * @brief: alloc memory
 * @param [in] bufferSize: bufferSize
 * @return: return buffer object
 */
VmiBuffer VmiBuffer::Alloc(size_t bufferSize)
{
    VmiBuffer buf = {};
    if (bufferSize == 0) {
        buf.m_pointer = nullptr;
    } else {
        buf.m_pointer = reinterpret_cast<uint8_t *>(malloc(bufferSize));
    }
    if (buf.m_pointer != nullptr) {
        buf.m_bufferSize = bufferSize;
    } else {
        buf.m_bufferSize = 0;
    }
    return buf;
}

/**
 * @brief: free memmory
 */
void VmiBuffer::Free()
{
    if (m_pointer != nullptr) {
        free(m_pointer);
        m_pointer = nullptr;
        m_bufferSize = 0;
    }
}

/**
 * @brief: alloc memory
 * @param [in] size: memory size
 * @return: memory pointer
 */
void* VmiAllocBuffer(const unsigned int size)
{
    void *buf = nullptr;
    if (size > 0) {
        buf = malloc(size);
    }
    if (buf == nullptr) {
        ERR("malloc failed");
    }
    return buf;
}

/**
 * @brief: free memory
 * @param [in] size: memory pointer
 */
void VmiFreeBuffer(void* buf)
{
    if (buf != nullptr) {
        free(buf);
        buf = nullptr;
    } else {
        ERR("VMIBUF: free buf(nullptr ptr) failed");
        return;
    }
}
